import path from 'path';
import fs from 'fs';
import fxExtra from 'fs-extra';

// 第二个参数必须传数组，哪怕只有一个元素
function analyse(result, componentList, repoPackageRoot) {
  let dependenciesOfComponentList = [];
  componentList.forEach((component) => {
    if (!result.includes(component)) {
      result.push(component);
      if (component === 'index.js') {
        const fileData = fs.readFileSync(path.join(repoPackageRoot, 'index.js'), 'utf8');
        // 因为 index.js 在根目录，所以依赖是 './countdown/index' 这种单点号
        const regExp = /(?<=['"]\.\/)[^'"\/]+?(?=\/)/g;
        const dependenciesOfComponent = fileData.match(regExp);
        if (dependenciesOfComponent) {
          dependenciesOfComponentList = dependenciesOfComponentList.concat(dependenciesOfComponent);
        }
      } else {
        const componentPath = path.join(repoPackageRoot, component);
        const fileList = fs.readdirSync(componentPath).filter((v) => fs.statSync(path.join(componentPath, v)).isFile());
        fileList.forEach((file) => {
          const fileData = fs.readFileSync(path.join(componentPath, file), 'utf8');
          // 正则注释：
          // 应避免命中 Wux 的 field 的 ../".concat(e,
          // https://github.com/wux-weapp/wux-weapp
          // 由用户自行判断是否使用 index.js
          // 应命中 Wux 的 xxx 的 require("../index/index") ，这个文件是根目录的 index 目录
          const regExp = /(?<=['"]\.\.\/)[^'"\/]+?(?=\/)/g;
          const dependenciesOfComponent = fileData.match(regExp);
          if (dependenciesOfComponent) {
            dependenciesOfComponentList = dependenciesOfComponentList.concat(dependenciesOfComponent);
          }
        });
      }
    }
  });
  dependenciesOfComponentList = [...new Set(dependenciesOfComponentList)];
  if (dependenciesOfComponentList.length) {
    return analyse.bind(this)(result, dependenciesOfComponentList, repoPackageRoot);
  }
  return result;
}

export function getDependencies(libInProj, repoPackageRoot) {
  return analyse.bind(this)([], libInProj.selectionList, repoPackageRoot);
}

export function copyComponent(from, to) {
  fxExtra.copySync(from, to, { overwrite: true });
}

export function removeComponent(to) {
  fxExtra.removeSync(to);
}
